import axios, { Method } from 'axios'
import { showToast } from 'vant'

const instance = axios.create({
  baseURL: 'xxx',
  timeout: 5000,
})

instance.interceptors.request.use(
  config => {
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  res => {
    if (res?.data?.code !== 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    return res
  },
  err => {
    return Promise.reject(err)
  }
)

const request = (url: string, method: Method = 'GET', submitData?: object) => {
  return instance.request({
    url,
    method,
    [method.toLocaleLowerCase() === 'get' ? 'params' : 'data']: submitData,
  })
}

export { request }
